package repository

import (
	"context"
	"demo/domain/model"
	"gorm.io/gorm"
	"time"
)

type transformEventRecordRepository struct {
	db *gorm.DB
}

func (t transformEventRecordRepository) QueryVisitStatisticsDuration(ctx context.Context, start, end time.Time) ([]*model.VisitStatistics, error) {
	var stats []*model.VisitStatistics
	// 构建查询
	err := t.db.WithContext(ctx).
		Model(&model.TransformEventRecord{}).
		Select(`
			COUNT(1) AS pv_count,
			COALESCE(COUNT(DISTINCT unique_identity), 0) AS uv_count,
			COALESCE(COUNT(DISTINCT client_ip), 0) AS ip_count,
			SUM(CASE WHEN transform_status = 3 THEN 1 ELSE 0 END) AS effective_redirection_count,
			SUM(CASE WHEN transform_status != 3 THEN 1 ELSE 0 END) AS ineffective_redirection_count,
			TO_CHAR(record_time, 'YYYY-MM-DD') AS statistics_date,
			compress_code AS compress_code,
			short_url_digest AS short_url_digest,
			long_url_digest AS long_url_digest,
			MAX(long_url) AS long_url
		`).
		Where("deleted = ?", 0).
		Where("record_time >= ?", start).
		Where("record_time <= ?", end).
		Group("compress_code, TO_CHAR(record_time, 'YYYY-MM-DD'), short_url_digest, long_url_digest").
		Scan(&stats).Error
	return stats, err
}

func (t transformEventRecordRepository) Save(ctx context.Context, entity *model.TransformEventRecord) error {
	return t.db.WithContext(ctx).Create(entity).Error
}

// NewTransformEventRecordRepository 创建一个新的 Repository 实例
func NewTransformEventRecordRepository(db *gorm.DB) model.TransformEventRecordRepository {
	return &transformEventRecordRepository{db: db}
}
